package com.zhangxun.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

import java.time.Duration;

@Configuration
public class RouteConfig {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Bean
    public RouteLocator routeLocator(RouteLocatorBuilder builder){
        //登录路由配置，将返回的token存放一份到redis当中。
       return builder.routes()
                .route("Loging-service-id",r->r.path("/oauth/token")
                        .filters(f->f.modifyResponseBody(String.class,String.class,(exchange,result)->{
                            JSONObject jsonObject = JSON.parseObject(result);
                            String token = jsonObject.getString("access_token");
                            if(StringUtils.hasText(token)){
                                stringRedisTemplate.opsForValue().set("bearer "+token,
                                        "", Duration.ofSeconds(jsonObject.getLong("expires_in")));
                            }
                            return Mono.just(result);}))
                        .uri("lb://auth-server"))
                .build();

    }
}
